package com.atgm.mall.gmmallclub.service.impl;

import com.atgm.common.constant.ClubConstant;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.ClubException;
import com.atgm.common.utils.PageUtils;
import com.atgm.common.utils.Query;
import com.atgm.mall.gmmallclub.dao.ArticleDao;
import com.atgm.mall.gmmallclub.entity.ArticleEntity;
import com.atgm.mall.gmmallclub.service.ArticleService;
import com.atgm.mall.gmmallclub.vo.resp.ArticleRespVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleDao, ArticleEntity> implements ArticleService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        IPage<ArticleEntity> page = this.page(new Query<ArticleEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public ArticleRespVo queryArticleInfoById(Long id) {
        ArticleRespVo articleRespVo = new ArticleRespVo();

        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        ArticleEntity clubArticleEntity = baseMapper.selectOne(queryWrapper);

        BeanUtils.copyProperties(clubArticleEntity, articleRespVo);
        return articleRespVo;
    }

    @Override
    public void updateViewCount(Long id) {
        //检查该文章是否存在
        if (!checkArticleIsExist(id)) {
            return;
        }

        //浏览数量+1
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("view_count", "id");
        queryWrapper.eq("id", id);
        ArticleEntity articleEntity = baseMapper.selectOne(queryWrapper);
        articleEntity.setViewCount(articleEntity.getViewCount() + 1);
        baseMapper.updateById(articleEntity);
    }

    /**
     * 检查文章是否存在
     * @param id
     * @return
     */
    private boolean checkArticleIsExist(Long id) {
        //未删除的文章
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count == 1;
    }

    @Override
    public void updateHotArticleList() {
        //获取浏览数量前10的文章
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "article_title", "def_img", "tag");
        queryWrapper.orderByDesc("view_count");
        IPage<ArticleEntity> page = new Page<ArticleEntity>(1, 10);
        IPage<ArticleEntity> iPage = baseMapper.selectPage(page, queryWrapper);
        List<ArticleEntity> list = iPage.getRecords();
        log.info("list : {}", list);
        try {
            redisTemplate.delete(ClubConstant.Redis.HOT_ARTICLE_LIST);
        } catch (Exception e) {
            log.error("删除热帖key键失败");
        }
        //间隔时间短 会出现重复数据
        redisTemplate.opsForValue().set(ClubConstant.Redis.HOT_ARTICLE_LIST, list);
    }

    @Override
    public List<ArticleEntity> queryHotArticle() {
        List<ArticleEntity> list = (List<ArticleEntity>) redisTemplate.opsForValue().get(ClubConstant.Redis.HOT_ARTICLE_LIST);
        return list;
    }

    @Override
    public void updateThumbsCount(Long id, Integer count) {
        //检查该文章是否存在
        if (!checkArticleIsExist(id)) {
            return;
        }
        if (0 == count) {  //点赞数量 -1
            Integer size = baseMapper.reduceThumbsCountById(id);
            if (size != 1) {
                throw new ClubException("取消点赞失败", BizCodeEnume.MEMBER_THUMBS.getCode());
            }
        }else {
            Integer size = baseMapper.increaseThumbsCountById(id);
            if (size != 1) {
                throw new ClubException("点赞失败", BizCodeEnume.MEMBER_THUMBS.getCode());
            }
        }
    }

    @Override
    public void updateCollectCount(Long id, Integer count) {
        //检查该文章是否存在
        if (!checkArticleIsExist(id)) {
            return;
        }

        if (0 == count) {//收藏数量 -1
            Integer size = baseMapper.reduceCollectCountById(id);
            if (size != 1) {
                throw new ClubException("取消收藏失败", BizCodeEnume.MEMBER_COLLECT.getCode());
            }
        }else {
            Integer size = baseMapper.increaseCollectCountById(id);
            if (size != 1) {
                throw new ClubException("收藏失败", BizCodeEnume.MEMBER_COLLECT.getCode());
            }
        }
    }

    @Override
    public void saveArticleInfo(ArticleEntity articleEntity) {
        articleEntity.setViewCount(0);
        articleEntity.setThumbsCount(0);
        articleEntity.setCommentCount(0);
        articleEntity.setCollectCount(0);
        articleEntity.setDeleted(0);  //是否删除
        articleEntity.setCreateTime(new Date());
        articleEntity.setUpdateTime(new Date());
        int count = baseMapper.insert(articleEntity);
        if (count != 1) {
            throw new ClubException("发布帖子失败", BizCodeEnume.PUBLISH_ARTICLE.getCode());
        }

        //TODO 通知粉丝 rabbitmq
    }
}
